package com.nyist.health.utils;

/**
 * @description ：
 * @version: 1.0
 */

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.FileInputStream;
import java.util.UUID;

/**
 * 七牛云工具类
 */
public class QiniuUtils {

    //域名：qdb44kz1s.bkt.clouddn.com
    //应该下发给  客户端的
//    public static String qiniu_img_url_pre = "http://psuyuqoog.bkt.clouddn.com/";
    public static String qiniu_img_url_pre = "http://qdcl5ccdf.bkt.clouddn.com/";
    //    public static String accessKey = "fhuiPBXFTZIgJdtZGuMtCUJ3zSrT7k3AHmVNE4UA";
    public static String accessKey = "zQhsORSPZEjZ6ri0C6PdJCJ8UBUy33KOsopzF7E-";
    //    public static String secretKey = "zKKxCW_HjQmwtl4JI80nMT0Ve2V7VZDbqT4zt_tT";
    public static String secretKey = "cSh_fIf7VAzhkmqs-P7iBSRaHglyYS9VNTQQZ4dT";
    //用户
    public static String bucket = "health-oms";

    /**
     * 上传文件
     *
     * @param bytes          文件内容，字节数组
     * @param uploadFileName 保存到服务端的文件名
     */
    public static void upload2Qiniu(byte[] bytes, String uploadFileName) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = uploadFileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果

												//键 是hash 值是 对文件内容的哈希结果，值是文件名
            System.out.println(response.bodyString());
            // 访问路径

            System.out.println("http://qdcl5ccdf.bkt.clouddn.com/" + uploadFileName);
//            System.out.println("http://psuyuqoog.bkt.clouddn.com/" + uploadFileName);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                ex.printStackTrace();
            }
        }
    }

    // 测试上传
    public static void main(String args[]) throws Exception {
        //代码测试 固定 上传
        String localFilePath = "F:\\2020idea\\health_pic_test\\abcd.jpg";
        FileInputStream fileInputStream = new FileInputStream(localFilePath);
        byte[] data = new byte[1024 * 1024];
        fileInputStream.read(data);
        String saveFileName = UUID.randomUUID().toString().replace("-", "");
        QiniuUtils.upload2Qiniu(data, saveFileName);
    }
}
